<template>
    <div class="item-in-batch-dialog">
        <TheElDialog
            ref="dialog"
            :title="title"
            :visible.sync="multipleAddVisible"
            minWidth
            v-bind="$attrs"
            v-on="$listeners"
        >
            <div v-loading="isMultipleLoading">
                <div v-if="isAdd">
                    <el-button style="width: 100%;margin-bottom: 10px;" type="primary" @click="onPushSelection"
                        >+1 行数据</el-button
                    >
                </div>
                <el-table
                    :data="multipleCreateSelection"
                    border
                    style="width: 100%"
                    :row-key="getRowKeys"
                    :expand-row-keys="expands"
                    :summary-method="getSummaries"
                    show-summary
                >
                    <el-table-column type="expand">
                        <template v-slot="props">
                            <div v-if="!isDetail">
                                <el-button
                                    style="width: 100%;margin-bottom: 10px;"
                                    type="plain"
                                    @click="onPushExpandSelection(props)"
                                    >+1 行数据</el-button
                                >
                            </div>
                            <el-table
                                :data="props.row.itemOutIns"
                                style="width: 100%;"
                                :summary-method="getSummaries"
                                show-summary
                                :row-key="getRowKeys"
                                border
                            >
                                <el-table-column type="index" width="50" label="序号"> </el-table-column>
                                <el-table-column prop="date" label="日期">
                                    <template v-slot:header
                                        ><span style="color:#f00;padding-right: 4px;">*</span>日期</template
                                    >
                                    <template v-slot="{row}">
                                        <el-form
                                            :key="`form_itemOutIns_date_${row.uuid}`"
                                            :ref="`form_itemOutIns_date_${row.uuid}`"
                                            :model="row"
                                            :rules="RULES"
                                        >
                                            <el-form-item prop="date" label="">
                                                <template v-if="isDetail">{{ row.date | formatShortDate }}</template>
                                                <el-date-picker
                                                    v-else
                                                    type="date"
                                                    placeholder="选择日期"
                                                    format="yyyy/MM/dd"
                                                    prefix-icon="false"
                                                    v-model="row.date"
                                                    :clearable="true"
                                                    class="form-the-datepicker"
                                                    style="width: 100%;"
                                                ></el-date-picker>
                                            </el-form-item>
                                        </el-form>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="itemOutInId" label="收支项目">
                                    <template v-slot:header
                                        ><span style="color:#f00;padding-right: 4px;">*</span>收支项目</template
                                    >
                                    <template v-slot="{row}">
                                        <el-form
                                            :key="`form_itemOutIns_itemOutInId_${row.uuid}`"
                                            :ref="`form_itemOutIns_itemOutInId_${row.uuid}`"
                                            :model="row"
                                            :rules="RULES"
                                        >
                                            <el-form-item prop="itemOutInId" label="">
                                                <template v-if="isDetail">{{
                                                    {id: row.itemOutInId, arr: optionsProjects} | findValue
                                                }}</template>

                                                <el-select
                                                    v-else
                                                    v-model="row.itemOutInId"
                                                    filterable
                                                    clearable
                                                    placeholder="请选择"
                                                    style="width: 100%"
                                                >
                                                    <template v-slot:empty>
                                                        <p class="el-select-dropdown__empty">
                                                            无匹配数据
                                                            <el-button
                                                                @click="multipleAddVisibleItemOutIn = true"
                                                                type="text"
                                                                style="padding: 0; font-size: inherit;"
                                                                ><i class="el-icon-plus"></i> 新增收支项目</el-button
                                                            >
                                                        </p>
                                                    </template>
                                                    <el-option
                                                        v-for="item in optionsProjects"
                                                        :key="item._id"
                                                        :label="item.name"
                                                        :value="item._id"
                                                    >
                                                    </el-option>
                                                </el-select>
                                            </el-form-item>
                                        </el-form>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="money" label="金额">
                                    <template v-slot:header
                                        ><span style="color:#f00;padding-right: 4px;">*</span>金额</template
                                    >
                                    <template v-slot="{row}">
                                        <el-form
                                            :key="`form_itemOutIns_money_${row.uuid}`"
                                            :ref="`form_itemOutIns_money_${row.uuid}`"
                                            :model="row"
                                            :rules="RULES"
                                        >
                                            <el-form-item prop="money" label="">
                                                <template v-if="isDetail">{{
                                                    row.money | keep2decimalPlaces
                                                }}</template>
                                                <el-input
                                                    v-else
                                                    type="number"
                                                    @mousewheel.native.prevent
                                                    @DOMMouseScroll.native.prevent
                                                    v-model="row.money"
                                                    placeholder=""
                                                    @keydown.shift.alt.down.native="
                                                        onKeydownItemOutIns('down', props, row, $event)
                                                    "
                                                    @keydown.shift.alt.up.native="
                                                        onKeydownItemOutIns('up', props, row, $event)
                                                    "
                                                    @paste.native="onPasteCapture(props, row, $event)"
                                                ></el-input>
                                            </el-form-item>
                                        </el-form>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="abstract" label="摘要">
                                    <template v-slot:header
                                        ><span style="color:#f00;padding-right: 4px;">*</span>摘要</template
                                    >
                                    <template v-slot="{row}">
                                        <el-form
                                            :key="`form_itemOutIns_abstract_${row.uuid}`"
                                            :ref="`form_itemOutIns_abstract_${row.uuid}`"
                                            :model="row"
                                            :rules="RULES"
                                        >
                                            <el-form-item prop="abstract" label="">
                                                <template v-if="isDetail">{{ row.abstract }}</template>
                                                <el-input
                                                    v-else
                                                    type="textarea"
                                                    rows="1"
                                                    :maxlength="200"
                                                    v-model="row.abstract"
                                                    placeholder=""
                                                    @keydown.shift.alt.down.native="
                                                        onKeydownItemOutIns('down', props, row, $event)
                                                    "
                                                    @keydown.shift.alt.up.native="
                                                        onKeydownItemOutIns('up', props, row, $event)
                                                    "
                                                ></el-input>
                                            </el-form-item>
                                        </el-form>
                                    </template>
                                </el-table-column>
                                <el-table-column v-if="!isDetail" align="center" label="操作" :width="50">
                                    <template v-slot="{row}">
                                        <el-button
                                            size="small"
                                            @click="onRemoveAddExpandSelection(props, row)"
                                            type="text"
                                        >
                                            移除
                                        </el-button>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </template>
                    </el-table-column>
                    <el-table-column type="index" width="50" label="序号"></el-table-column>
                    <el-table-column prop="documentNo" label="单据编号*" width="183">
                        <template v-slot:header><span style="color:#f00;padding-right: 4px;">*</span>单据编号</template>
                        <template v-slot="{row}">
                            <el-form
                                @submit.native.prevent
                                :key="`form_documentNo_${row.uuid}`"
                                :ref="`form_documentNo_${row.uuid}`"
                                :model="row"
                                :rules="RULES"
                            >
                                <el-form-item prop="documentNo" label="">
                                    <template v-if="isDetail">{{ row.documentNo }}</template>
                                    <el-input
                                        v-else
                                        class="textvalue"
                                        :disabled="true"
                                        v-model="row.documentNo"
                                        placeholder=""
                                        :title="row.documentNo"
                                    ></el-input>
                                </el-form-item>
                            </el-form>
                        </template>
                    </el-table-column>
                    <el-table-column prop="documentDate" label="单据日期*">
                        <template v-slot:header><span style="color:#f00;padding-right: 4px;">*</span>单据日期</template>
                        <template v-slot="{row}">
                            <el-form
                                @submit.native.prevent
                                :key="`form_documentDate_${row.uuid}`"
                                :ref="`form_documentDate_${row.uuid}`"
                                :model="row"
                                :rules="RULES"
                            >
                                <el-form-item prop="documentDate" label="">
                                    <template v-if="isDetail">{{ row.documentDate | formatDateFillStr }}</template>

                                    <TheDatePicker v-else v-model="row.documentDate"></TheDatePicker>
                                </el-form-item>
                            </el-form>
                        </template>
                    </el-table-column>
                    <el-table-column prop="depot" label="仓库*">
                        <template v-slot:header><span style="color:#f00;padding-right: 4px;">*</span>仓库</template>
                        <template v-slot="{row}">
                            <el-form
                                @submit.native.prevent
                                :key="`form_depot_${row.uuid}`"
                                :ref="`form_depot_${row.uuid}`"
                                :model="row"
                                :rules="RULES"
                            >
                                <el-form-item prop="depot" label="">
                                    <template v-if="isDetail">{{
                                        {id: row.depot, arr: optionsDepots} | findValue
                                    }}</template>
                                    <el-select
                                        v-else
                                        v-model="row.depot"
                                        filterable
                                        clearable
                                        placeholder="请选择"
                                        style="width: 100%"
                                    >
                                        <el-option
                                            v-for="item in optionsDepots"
                                            :key="item._id"
                                            :label="item.name"
                                            :value="item._id"
                                        >
                                        </el-option>
                                    </el-select>
                                </el-form-item>
                            </el-form>
                        </template>
                    </el-table-column>
                    <el-table-column prop="customer" label="客户">
                        <template v-slot:header><span style="color:#f00;padding-right: 4px;">*</span>客户</template>
                        <template v-slot="{row}">
                            <el-form
                                @submit.native.prevent
                                :key="`form_customer_${row.uuid}`"
                                :ref="`form_customer_${row.uuid}`"
                                :model="row"
                                :rules="RULES"
                            >
                                <el-form-item prop="customer" label="">
                                    <template v-if="isDetail">{{
                                        {id: row.customer, arr: optionsCustomers} | findValue
                                    }}</template>
                                    <el-select
                                        v-else
                                        v-model="row.customer"
                                        filterable
                                        clearable
                                        placeholder="请选择"
                                        style="width: 100%"
                                    >
                                        <template v-slot:empty>
                                            <p class="el-select-dropdown__empty">
                                                无匹配数据
                                                <el-button
                                                    @click="multipleAddVisibleCustomer = true"
                                                    type="text"
                                                    style="padding: 0; font-size: inherit;"
                                                    ><i class="el-icon-plus"></i> 新增客户</el-button
                                                >
                                            </p>
                                        </template>
                                        <el-option
                                            v-for="item in optionsCustomers"
                                            :key="item._id"
                                            :label="item.name"
                                            :value="item._id"
                                        >
                                        </el-option>
                                    </el-select>
                                </el-form-item>
                            </el-form>
                        </template>
                    </el-table-column>
                    <el-table-column prop="person" label="财务人员">
                        <template v-slot:header><span style="color:#f00;padding-right: 4px;">*</span>财务人员</template>
                        <template v-slot="{row}">
                            <el-form
                                @submit.native.prevent
                                :key="`form_person_${row.uuid}`"
                                :ref="`form_person_${row.uuid}`"
                                :model="row"
                                :rules="RULES"
                            >
                                <el-form-item prop="person" label="">
                                    <template v-if="isDetail">{{
                                        {id: row.person, arr: optionsPersons} | findValue
                                    }}</template>
                                    <el-select
                                        v-else
                                        v-model="row.person"
                                        filterable
                                        clearable
                                        placeholder="请选择"
                                        style="width: 100%"
                                    >
                                        <el-option
                                            v-for="item in optionsPersons"
                                            :key="item._id"
                                            :label="item.name"
                                            :value="item._id"
                                        >
                                        </el-option>
                                    </el-select>
                                </el-form-item>
                            </el-form>
                        </template>
                    </el-table-column>

                    <el-table-column prop="account" label="账户名称">
                        <template v-slot:header><span style="color:#f00;padding-right: 4px;">*</span>账户名称</template>
                        <template v-slot="{row}">
                            <el-form
                                @submit.native.prevent
                                :key="`form_account_${row.uuid}`"
                                :ref="`form_account_${row.uuid}`"
                                :model="row"
                                :rules="RULES"
                            >
                                <el-form-item prop="account" label="">
                                    <template v-if="isDetail">{{
                                        {id: row.account, arr: optionsAccounts} | findValue
                                    }}</template>
                                    <el-select
                                        v-else
                                        v-model="row.account"
                                        filterable
                                        clearable
                                        placeholder="请选择"
                                        style="width: 100%"
                                    >
                                        <el-option
                                            v-for="item in optionsAccounts"
                                            :key="item._id"
                                            :label="item.name"
                                            :value="item._id"
                                        >
                                        </el-option>
                                    </el-select>
                                </el-form-item>
                            </el-form>
                        </template>
                    </el-table-column>
                    <el-table-column prop="total" label="单据金额" width="100">
                        <template v-slot="{row}">
                            <el-form
                                @submit.native.prevent
                                :key="`form_total_${row.uuid}`"
                                :ref="`form_total_${row.uuid}`"
                                :model="row"
                                :rules="RULES"
                            >
                                <el-form-item prop="total" label="">
                                    <template v-if="isDetail">{{ row.total | keep2decimalPlaces }}</template>
                                    <el-input
                                        v-else
                                        class="textvalue"
                                        type="number"
                                        :disabled="true"
                                        @mousewheel.native.prevent
                                        @DOMMouseScroll.native.prevent
                                        v-model="row.total"
                                    ></el-input>
                                </el-form-item>
                            </el-form>
                        </template>
                    </el-table-column>
                    <el-table-column prop="remark" label="备注">
                        <template v-slot="{row}">
                            <el-form
                                @submit.native.prevent
                                :key="`form_remark_${row.uuid}`"
                                :ref="`form_remark_${row.uuid}`"
                                :model="row"
                                :rules="RULES"
                            >
                                <el-form-item prop="remark" label="">
                                    <template v-if="isDetail">{{ row.remark }}</template>
                                    <el-input
                                        v-else
                                        type="textarea"
                                        rows="1"
                                        :show-word-limit="row.remark ? row.remark && row.remark.length > 150 : false"
                                        :maxlength="200"
                                        v-model="row.remark"
                                        placeholder=""
                                        @keydown.shift.alt.down.native="onKeydownTableRow('down', row, $event)"
                                        @keydown.shift.alt.up.native="onKeydownTableRow('up', row, $event)"
                                    ></el-input>
                                </el-form-item>
                            </el-form>
                        </template>
                    </el-table-column>
                    <el-table-column v-if="!isDetail" align="center" label="操作" :width="50">
                        <template v-slot="{row}">
                            <el-button size="small" @click="onRemoveAddSelection(row)" type="text">
                                移除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button :disabled="isMultipleLoading" @click="multipleAddVisible = false">取 消</el-button>
                <el-button v-if="isDetail" type="primary" plain @click="onClickPrint('dialog')">打 印</el-button>
                <el-button
                    v-else
                    :disabled="isDetail"
                    :loading="isMultipleLoading"
                    type="primary"
                    @click="onClickMultipleOkCreate(multipleCreateSelection, $refs)"
                    >确 定</el-button
                >
            </span>
        </TheElDialog>
        <BatchCustomerDialog
            type="add"
            title="批量添加客户"
            :visible.sync="multipleAddVisibleCustomer"
            :isLoading.sync="isMultipleLoading"
            @on-ok="$emit('refresh-options')"
        ></BatchCustomerDialog>
        <BatchItemOutInDialog
            type="add"
            title="批量添加收支项目"
            :visible.sync="multipleAddVisibleItemOutIn"
            :isLoading.sync="isMultipleLoading"
            @on-ok="$emit('refresh-options')"
        ></BatchItemOutInDialog>
    </div>
</template>
<script>
import {postApisList, putApisList} from '@/api/itemIn';
import {v4 as uuidv4} from 'uuid';
import getRules, {formValidates} from '@/views/financial/getRules';
import dialogToPrint from '@/utils/dialogToPrint';
import moment from 'moment';
import BatchCustomerDialog from '@/views/system/customer/BatchDialog';
import BatchItemOutInDialog from '@/views/system/item-out-in/BatchDialog';

const dataSourceDefault = {
    id: undefined,
    documentNo: `SR${moment().format('YYYYMMDDHHmmssSSS')}`,
    documentDate: undefined,
    customer: undefined,
    person: undefined,
    remark: undefined,
    account: undefined,
    total: undefined,
    depot: undefined,
    itemOutIns: [
        {
            uuid: uuidv4(),
            itemOutInId: undefined,
            date: new Date().toISOString(),
            money: undefined,
            abstract: ''
        }
    ]
};
export default {
    name: 'BatchDialog',
    components: {BatchCustomerDialog, BatchItemOutInDialog},
    props: {
        type: {type: String, default: 'add'}, // type === "add" 添加, type === "edit" 编辑, type === 'detail' 详情
        title: {type: String, default: '批量添加'},
        visible: {type: Boolean, default: false, required: true},
        multipleSelection: {type: Array, required: false, default: () => []},
        tableData: {type: Array, required: false, default: () => []},
        isLoading: {type: Boolean, default: false, required: true},
        onRemoveUpdateSelection: {type: Function, default: () => () => {}, required: false},

        optionsProjects: {type: Array, required: true, default: () => []},
        optionsDepots: {type: Array, required: true, default: () => []},
        optionsCustomers: {type: Array, required: true, default: () => []},
        optionsAccounts: {type: Array, required: true, default: () => []},
        optionsPersons: {type: Array, required: true, default: () => []},

        initialCopyData: {type: Array, required: false, default: () => []}
    },
    data() {
        return {
            RULES: getRules(),
            multipleCreateSelection: [
                {...dataSourceDefault, uuid: uuidv4()},
                {...dataSourceDefault, uuid: uuidv4()}
            ],
            expands: [],
            getRowKeys(row) {
                return row.uuid;
            },
            multipleAddVisibleCustomer: false, // 供应商
            multipleAddVisibleItemOutIn: false // 收支项目
        };
    },
    computed: {
        multipleAddVisible: {
            get() {
                return this.visible;
            },
            set(val) {
                this.$emit('update:visible', val);
            }
        },
        isMultipleLoading: {
            get() {
                return this.isLoading;
            },
            set(val) {
                this.$emit('update:isLoading', val);
            }
        },
        isEdit() {
            return this.type === 'edit';
        },
        isDetail() {
            return this.type === 'detail';
        },
        isAdd() {
            return this.type === 'add';
        }
    },
    watch: {
        multipleAddVisible: {
            handler(val) {
                if (!(val && this.isAdd)) {
                    return;
                }

                if (this.initialCopyData.length > 0) {
                    this.multipleCreateSelection = this.initialCopyData;
                } else {
                    const uuid = uuidv4();
                    this.multipleCreateSelection = [
                        {
                            ...dataSourceDefault,
                            itemOutIns: dataSourceDefault.itemOutIns.map(item => ({...item, uuid: uuidv4()})),
                            documentNo: `SR${moment().format('YYYYMMDDHHmmss')}${moment().format('SSS')}${uuid.slice(
                                -6
                            )}`,
                            uuid
                        }
                    ];
                }

                const selection = this.multipleCreateSelection;
                const selectionLength = selection.length;
                this.expands = selectionLength > 0 ? [selection[selection.length - 1].uuid] : [];
            },
            deep: true,
            immediate: true
        },
        multipleSelection: {
            handler(val) {
                if (this.isEdit || this.isDetail) {
                    this.multipleCreateSelection = val || [];
                }
            },
            deep: true,
            immediate: true
        }
    },
    methods: {
        onPasteCapture(props, row, event) {
            const clip = event.clipboardData.getData('Text');
            if (!clip) {
                return;
            }
            let arr = clip.trim().split('\r\n');
            arr = arr.map(item => {
                const str = item.trim();
                return str.length > 0 ? str - 0 : str;
            });
            const isValid = arr.filter(item => item).every(item => typeof item === 'number' && !Number.isNaN(item));

            if (!arr.includes(NaN) && arr.length > 1 && isValid) {
                this.$confirm(`此操作将覆盖粘贴${arr.length}条数据, 是否继续?`, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                })
                    .then(() => {
                        const hitIndex = props.row.itemOutIns.findIndex(item => item.uuid === row.uuid);
                        const slicedata = props.row.itemOutIns.slice(hitIndex);
                        arr.forEach((item, index) => {
                            if (slicedata[index]) {
                                slicedata[index].money = item;
                            }
                        });

                        props.row.itemOutIns = [...props.row.itemOutIns.slice(0, hitIndex), ...slicedata];

                        event.preventDefault();
                    })
                    .catch(() => {});
            }
        },
        async onKeydownTableRow(value, row, event) {
            if (!this.isAdd) {
                return;
            }

            await this.$nextTick();
            const tableData = [...this.multipleCreateSelection];
            const hitIndex = tableData.findIndex(item => item.uuid === row.uuid);
            // 如果为真，那么日期自动+1天
            const ctrlKey = event.ctrlKey;
            const newItem = {
                ...row,
                _id: undefined,
                uuid: uuidv4(),
                itemOutIns: row.itemOutIns.map(item => ({...item, _id: undefined, id: undefined, uuid: uuidv4()})),
                documentNo: `SR${moment().format('YYYYMMDDHHmmssSSS')}`
            };

            // eslint-disable-next-line
            const handleDate = (num, key = 'days') =>
                ctrlKey && row.documentDate // eslint-disable-line
                    ? new Date(moment(new Date(row.documentDate)).add(num, key)) // eslint-disable-line
                    : row.documentDate; // eslint-disable-line

            if (value === 'up') {
                row.documentDate = handleDate(-1);
                tableData.splice(hitIndex + 1, 0, newItem);
            }
            if (value === 'down') {
                row.documentDate = handleDate(1);
                if (hitIndex !== -1) {
                    tableData.splice(hitIndex, 0, newItem);
                }
            }
            this.multipleCreateSelection = tableData;
            await this.$nextTick();
            this.expands = [row.uuid];
        },
        async onKeydownItemOutIns(value, props, row, event) {
            await this.$nextTick();
            const itemOutIns = [...props.row.itemOutIns];
            const hitIndex = itemOutIns.findIndex(item => item.uuid === row.uuid);
            // 如果为真，那么日期自动+1天
            const ctrlKey = event.ctrlKey;
            const newItem = {
                uuid: uuidv4(),
                date: row.date,
                itemOutInId: row.itemOutInId,
                money: row.money,
                abstract: row.abstract
            };

            if (value === 'up') {
                row.date = ctrlKey && row.date ? new Date(moment(new Date(row.date)).add(-1, 'days')) : row.date;
                itemOutIns.splice(hitIndex + 1, 0, newItem);
            }
            if (value === 'down') {
                row.date = ctrlKey && row.date ? new Date(moment(new Date(row.date)).add(1, 'days')) : row.date;
                if (hitIndex !== -1) {
                    itemOutIns.splice(hitIndex, 0, newItem);
                }
            }
            props.row.itemOutIns = itemOutIns;
        },
        onPushSelection() {
            this.$nextTick(() => {
                const newItem = {
                    ...dataSourceDefault,
                    itemOutIns: dataSourceDefault.itemOutIns.map(item => ({...item, uuid: uuidv4()})),
                    documentNo: `SR${moment().format('YYYYMMDDHHmmssSSS')}`,
                    uuid: uuidv4()
                };
                this.multipleCreateSelection.push(newItem);
                this.expands = [newItem.uuid];
            });
        },
        onPushExpandSelection({row}) {
            this.$nextTick(() => {
                row.itemOutIns.push({
                    uuid: uuidv4(),
                    itemOutInId: undefined,
                    date: new Date().toISOString(),
                    money: undefined,
                    abstract: ''
                });
            });
        },
        onRemoveAddExpandSelection(props, row) {
            props.row.itemOutIns = props.row.itemOutIns.filter(({uuid}) => uuid !== row.uuid);
        },
        getSummaries(param) {
            const {columns, data} = param;
            const sums = [];
            columns.forEach((column, index) => {
                if (index === 0) {
                    sums[index] = '合计';
                    return;
                }
                const values = data.map(item => Number(item[column.property]));
                if (column.property === 'money' || column.property === 'total') {
                    sums[index] = values.reduce((prev, curr) => {
                        const value = Number(curr);
                        if (!isNaN(value)) {
                            return prev + curr;
                        } else {
                            return prev;
                        }
                    }, 0);
                    sums[index] = `¥ ${sums[index].toFixed(2)}`;
                } else {
                    // sums[index] = 'N/A';
                    sums[index] = '';
                }
            });

            return sums;
        },
        onRemoveAddSelection(row) {
            if (this.isEdit) {
                this.onRemoveUpdateSelection(row);
                return;
            }
            this.multipleCreateSelection = this.multipleCreateSelection.filter(({uuid}) => uuid !== row.uuid);
        },
        // 批量添加
        async onClickMultipleOkCreate(multipleCreateSelection, refs) {
            this.expands = multipleCreateSelection.map(item => item.uuid);
            await Promise.resolve(() => {});
            if (this.isEdit) {
                this.onClickMultipleOkUpdate(multipleCreateSelection, refs);
                return;
            }
            if (multipleCreateSelection.length === 0) {
                this.$message({showClose: true, type: 'error', message: '数据为空，批量添加失败'});
                return;
            }
            try {
                await formValidates.call(
                    this,
                    [
                        ...multipleCreateSelection,
                        ...multipleCreateSelection.reduce((acc, item) => {
                            return acc.concat(item.itemOutIns);
                        }, [])
                    ],
                    refs
                );

                this.isMultipleLoading = true;
                postApisList(multipleCreateSelection)
                    .then(res => {
                        this.multipleAddVisible = false;
                        this.$message({showClose: true, type: 'success', message: '批量添加成功'});
                        this.$emit('on-ok', true);
                    })
                    .catch(error => {
                        const data = error.response && error.response.data;
                        if (data && data.error) {
                            this.$message({showClose: true, type: 'error', message: data.error});
                        } else {
                            this.$message({showClose: true, type: 'error', message: '批量添加失败'});
                        }
                        console.error(error);
                    })
                    .finally(() => {
                        this.isMultipleLoading = false;
                    });
            } catch (error) {
                console.warn('表单的校验失败');
                this.$message({showClose: true, type: 'warn', message: '表单的校验失败'});
            }
        },
        // 批量修改
        async onClickMultipleOkUpdate(multipleSelection, refs) {
            if (multipleSelection.length === 0) {
                this.$message({showClose: true, type: 'error', message: '数据为空，批量修改失败'});
                return;
            }
            try {
                await formValidates.call(
                    this,
                    [
                        ...multipleSelection,
                        ...multipleSelection.reduce((acc, item) => {
                            return acc.concat(item.itemOutIns);
                        }, [])
                    ],
                    refs
                );
                this.isMultipleLoading = true;
                putApisList(multipleSelection)
                    .then(res => {
                        this.multipleAddVisible = false;
                        this.$message({showClose: true, type: 'success', message: '批量修改成功'});
                        this.$emit('on-ok', true);
                    })
                    .catch(error => {
                        const data = error.response && error.response.data;
                        if (data && data.error) {
                            this.$message({showClose: true, type: 'error', message: data.error});
                        } else {
                            this.$message({showClose: true, type: 'error', message: '批量修改失败'});
                        }
                        console.error(error);
                    })
                    .finally(() => {
                        this.isMultipleLoading = false;
                    });
            } catch (error) {
                console.warn('表单的校验失败');
                this.$message({showClose: true, type: 'warn', message: '表单的校验失败'});
            }
        },
        onClickPrint() {
            dialogToPrint.call(this, this.$refs.dialog, [
                ...Array.from(document.querySelectorAll('.dialog-footer')),
                ...Array.from(document.querySelectorAll('.el-dialog__close'))
            ]);
        }
    }
};
</script>
